package com.cskaoyan.wordmemorize.service.impl;

import com.aliyuncs.ram.model.v20150501.ListUsersResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.converter.PayConverter;
import com.cskaoyan.wordmemorize.dao.entity.GoodsDO;
import com.cskaoyan.wordmemorize.dao.entity.UserDO;
import com.cskaoyan.wordmemorize.dao.entity.UserVocBoundStatisticsDO;
import com.cskaoyan.wordmemorize.dao.entity.VocPaySaleDO;
import com.cskaoyan.wordmemorize.dao.mapper.GoodsMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocBoundStatisticsMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocPaySaleMapper;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.PayOrderDTO;
import com.cskaoyan.wordmemorize.dto.app.VocPaySaleDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.PaySuccessNotifyCommand;
import com.cskaoyan.wordmemorize.request.VocPaySaleCommand;
import com.cskaoyan.wordmemorize.service.UserPayService;
import jakarta.annotation.Resource;
import org.mapstruct.ap.shaded.freemarker.template.utility.NormalizeNewlines;
import org.springframework.stereotype.Service;


@Service
public class UserPayServiceImpl implements UserPayService {
    @Resource
    private VocPaySaleMapper vocPaySaleMapper;

    @Resource
    private PayConverter payConverter;

    @Resource
    UserVocBoundStatisticsMapper userVocBoundStatisticsMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    GoodsMapper goodsMapper;



    //用户用于支付
    @Override
    public PayOrderDTO pay(VocPaySaleCommand command, Long userId) {
        //新建个PayOrderDTO对象
        PayOrderDTO payOrderDTO = new PayOrderDTO();
        //创建个VocPaySaleDO对象
        VocPaySaleDO vocPaySaleDO = new VocPaySaleDO();
          //设置VocPaySaleDo的值
        vocPaySaleDO.setUserId(userId);
        vocPaySaleDO.setItemId( Long.parseLong( command.getItemId() ) );
        vocPaySaleDO.setItemName( command.getItemName() );
        vocPaySaleDO.setItemType( command.getItemType() );
        vocPaySaleDO.setPayPrice( command.getPayPrice() );
        vocPaySaleDO.setStatus(1);
        //把这个数据放入数据库（voc_pay_sale表中）
        vocPaySaleMapper.insert(vocPaySaleDO);
//        //获取支付交易的Id和金额（通过user_id在voc_pay_sale表中获取）
//          //建造条件构造器
//        LambdaQueryWrapper<VocPaySaleDO> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(VocPaySaleDO::getUserId, userId);
//        //查询
//        VocPaySaleDO paySaleDO = userPaySaleMapper.selectOne(wrapper);
//        Long id = vocPaySaleDO.getId();
        //设置值
        payOrderDTO.setId(String.valueOf(vocPaySaleDO.getId()));
        payOrderDTO.setTotalAmount(vocPaySaleDO.getPayPrice());
        payOrderDTO.setSubject(vocPaySaleDO.getItemName());
        if (command.getIsSignCard() ){
            UserDO userDO = new UserDO();
            userDO.setId(userId);
            userDO.setHasSignCard(1);
            userMapper.updateById(userDO);
        }else {
            //获取增加的单词上限
            String itemId = command.getItemId();
            //去goods里查询value值
            LambdaQueryWrapper<GoodsDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GoodsDO::getId,itemId);
            GoodsDO goodsDO = goodsMapper.selectOne(wrapper);
            Integer value = goodsDO.getValue();
            if (value == null){
                UserDO userDO = new UserDO();
                userDO.setId(userId);
                userDO.setHasSignCard(1);
                userMapper.updateById(userDO);
            }else {
            //让数据库中的total值增加exchangeVocCount个数量
            userVocBoundStatisticsMapper.updateByUserId(value,userId);}
        }
        return payOrderDTO;
    }


    //用户用于接收支付成功的异步通知
    @Override
    public String paySuccess(PaySuccessNotifyCommand command, Long userId) {
        //新建个VocPaySaleDO对象
        VocPaySaleDO vocPaySaleDO = new VocPaySaleDO();
        //进行赋值
        vocPaySaleDO.setId(command.getId());
        vocPaySaleDO.setStatus(command.getTradeStatus().equals("TRADE_SUCCESS") ? 2 : 1);
        vocPaySaleDO.setUserId(userId);
        vocPaySaleDO.setPayPrice(command.getTotalAmount());
        //更新数据库中
        vocPaySaleMapper.updateById(vocPaySaleDO);
        return "支付成功！";
    }

    //用户用于获取支付结果
    @Override
    public Integer queryTradeStatus(Long paySaleId) {
        LambdaQueryWrapper<VocPaySaleDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VocPaySaleDO::getId, paySaleId);
        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectOne(wrapper);
        if (vocPaySaleDO != null) {
            return vocPaySaleDO.getStatus();
        }
        return 1;
    }

    //用户用于查看购买历史
    @Override
    public PageDTO<VocPaySaleDTO> getPaySaleHistory(Long userId, PageRequest pageRequest) {
        //通过userId在voc_pay_sale表中查询此用户的多条数据(分页)
        LambdaQueryWrapper<VocPaySaleDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VocPaySaleDO::getUserId, userId);
        //判断是否分页
        if (pageRequest == null || pageRequest.getPageNum() == null || pageRequest.getCount() == null) {
            vocPaySaleMapper.selectList(null);
            return payConverter.vocPaySalePage2PageDTO(vocPaySaleMapper.selectList(null), 1L);
        }
        //新建个分页参数
        Page<VocPaySaleDO> pageDO = new Page<VocPaySaleDO>(pageRequest.getPageNum(), pageRequest.getCount());
        Page<VocPaySaleDO> page = vocPaySaleMapper.selectPage(pageDO, wrapper);

        PageDTO<VocPaySaleDTO> vocPaySaleDTOPageDTO = payConverter.vocPaySalePage2PageDTO(page.getRecords(), page.getTotal());

        return vocPaySaleDTOPageDTO;
    }
}
